package com.mall.order.mq.delay;

import com.mall.order.OrderCoreService;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CancelOrderRequest;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.swing.text.StyleConstants;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

/**
 * @author lxy
 * @create 2021-11-03 17:07
 */
@Component
public class DelayOrderCancelConsumer {

    DefaultMQPushConsumer consumer;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderCoreService orderCoreService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("delay_order_cancel_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                // 1.首先从消息中取出orderId
                // 2.查询orderId对应订单状态，如果订单的状态是已支付或已取消（什么都不做）
                // 3.如果订单的状态还是一个初始化状态，意味着用户还没支付，我们就可以取消订单
                //   a.修改订单状态为已取消
                //   b.还原可售卖库存：遍历被取消的订单中的订单商品条目，-lock_count,+sotck_count
                if (list.get(0).getMsgId() == null) return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                String orderId = new String(list.get(0).getBody(), StandardCharsets.UTF_8);
                if ("".equals(orderId)) return ConsumeConcurrentlyStatus.RECONSUME_LATER;

                Order order = orderMapper.selectByPrimaryKey(orderId);
                if (order == null) return ConsumeConcurrentlyStatus.RECONSUME_LATER;

                if (order.getStatus() != null){
                    // 取消订单
                    if (order.getStatus().equals(OrderConstants.ORDER_STATUS_INIT)){
                        CancelOrderRequest request = new CancelOrderRequest();
                        request.setOrderId(orderId);
                        orderCoreService.cancelOrder(request);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        try {
            consumer.subscribe("delay_order_cancel","*");
            consumer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
